package com.netty.time;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

/**
 * Package Name:com.my.time
 * Description: That's the purpose of the file
 * Date:2016/8/23 17:45
 * Copyright (c) 2016, zhongmu@suneee.com All Rights Reserved.
 */
public class TimeServerHandler extends ChannelHandlerAdapter {

    //通道读取
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //消息转ByteBuf
        ByteBuf  buf = (ByteBuf) msg;

        //byteBuf 中获取可读字节流，并构建新buf
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);

        //服务器获取到的请求体
        String body = new String (req,"UTF-8");
        System.out.println("the time server receive order : " + body);

        //判断是否是bad请求
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"BAD ORDER";

        //组装响应体
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());

        ctx.write(resp);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
